package com.example.student.web.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/**
 * @author TonySong
 * @date 2025/8/15 0015
 * @time 17:14
 */
@WebFilter("/*")
public class RepeatFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //转换为HTTP的请求和响应
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;
        //设置请求和响应编码方式是utf-8（防止出现中文乱码）
        resp.setContentType("text/html;charset-utf-8");
        req.setCharacterEncoding("utf-8");
        //获取页面（前台）的token
        String clientToken =req.getParameter("token");
        if(clientToken==null){
            chain.doFilter(req, resp);
        }else{
            //得到（创建）Session
            HttpSession session=req.getSession();
            String serverToken = (String)session.getAttribute("token");
            //如果服务器有token或者服务器的token和客户端的token相同
            if(serverToken!=null && clientToken.equals(serverToken)){
                System.out.println("检测到重复提交");
                resp.sendRedirect(req.getContextPath()+"/repeat.jsp");
            }else{
                session.setAttribute("token", clientToken);
                chain.doFilter(req, resp);
            }
        }
    }
}
